package com.wzd.imservice.service.impl;

import com.wzd.commonutils.R;
import com.wzd.imservice.entity.Mine;
import com.wzd.imservice.enums.ChatTypeEnum;
import com.wzd.imservice.enums.OnlineStatusEnum;
import com.wzd.imservice.service.MineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @ClassName MineService
 * @Author lofxve
 * @Date 2021/4/16 11:30
 * @Version 1.0
 */
@Service
public class MineServiceimpl implements MineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public R save(Mine mine) {
        // 类型 朋友
        mine.setType(ChatTypeEnum.getNameByKey(0));
        // 在线状态
        mine.setOnline(OnlineStatusEnum.getNameByKey(0));
        Mine save = mongoTemplate.save(mine);
        if (save.getId() != null) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    public R updateMine(Mine mine) {
        Query query = new Query(Criteria.where("_id").is(mine.getId()));
        Update update = new Update();

        if (!StringUtils.isEmpty(mine.getName())) {
            update.set("name", mine.getName());
        }
        if (!StringUtils.isEmpty(mine.getType())) {
            update.set("type", mine.getType());
        }
        if (!StringUtils.isEmpty(mine.getOnline())) {
            update.set("online", mine.getOnline());
        }
        if (!StringUtils.isEmpty(mine.getAvatar())) {
            update.set("avatar", mine.getAvatar());
        }
        if (!StringUtils.isEmpty(mine.getRole())) {
            update.set("role", mine.getRole());
        }
        mongoTemplate.updateFirst(query, update, Mine.class);
        return R.ok();
    }

    public R deleteById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query, Mine.class);
        return R.ok();
    }

    public Mine getMineById(String id) {
        Mine byId = mongoTemplate.findById(id, Mine.class);
        return byId;
    }

    @Override
    public List<Mine> getAllMine() {
        return mongoTemplate.findAll(Mine.class);
    }
}
